const path = require('path');
const Koa = require('koa');
const static_server = require('koa-static');
const http = require('http');
const socketIO = require('socket.io');

const socketConnectMapManager = require('./socketConnectMapManager');
const userInfoManager = require('./userInfoManager');
const { userInfo } = require('os');

const hostname = '127.0.0.1';
const port = 3000
const publicPath = path.join(__dirname, 'public');

// 创建koa实例
const app = new Koa(); //充当 http server

// 创建http server实例
const server = http.createServer(app.callback());

// 创建socket.io实例
const io = socketIO(server);

// 静态资源路由
app.use(static_server(publicPath));

//添加几个初始用户
function myInit() {
    userA = new userInfoManager.UserInfo(userName = 'zb', password = '123', isOnline = false);
    userB = new userInfoManager.UserInfo(userName = 'csy', password = '123', isOnline = false);
    userC = new userInfoManager.UserInfo(userName = 'www', password = '123', isOnline = false);
    userD = new userInfoManager.UserInfo(userName = 'abc', password = '123', isOnline = false);


    userInfoManager.addUserInfo('zb', userA);
    userInfoManager.addUserInfo('csy', userB);
    userInfoManager.addUserInfo('www', userC);
    userInfoManager.addUserInfo('abc', userD);


    userInfoManager.addFriend('zb', 'csy');
    userInfoManager.addFriend('zb', 'www');

    userInfoManager.addMessage(new userInfoManager.Message('zb', 'csy', 'hello csy', Date.now()));
    userInfoManager.addMessage(new userInfoManager.Message('csy', 'zb', 'how are you, zb', Date.now()));

    userInfoManager.addMessage(new userInfoManager.Message('zb', 'www', 'hello www', Date.now()));
    userInfoManager.addMessage(new userInfoManager.Message('www', 'zb', 'what\'s up man? ', Date.now()));



    console.log('');
}
myInit();
// 客户端连入
io.on('connection', (socket) => {
    const name = socket.handshake.query.name;
    const password = socket.handshake.query.password;
    const busness = socket.handshake.query.busness;

    console.log(`${name} connected`);

    // 请求注册
    if (busness === 'register') {
        let userInfo = new userInfoManager.UserInfo();
        userInfo.userName = name;
        userInfo.password = password;

        // 注册，加入此用户信息
        if (!userInfoManager.addUserInfo(name, userInfo)) {
            // 返回登录结果
            socket.emit('register_result', { register: false });
            console.log(`${name} register failed`);
            socketListenOn(socket);
            return;
        }
        socket.emit('register_result', { register: true });
        console.log(`${name} register successfully`);
        socketListenOn(socket);

        return;
    }
    // 请求登录
    else {
        // 检查用户名密码
        if (!userInfoManager.checkPassword(name, password)) {
            console.log(`${name} password is incorrect`);
            // 登录失败
            socket.emit('login_result', { login: false });
            socket.disconnect();
            return;
        }
        // 登录成功
        socket.emit('login_result', { login: true });
        console.log(`${name} login successfully`);

        // 存入socket信息
        socketConnectMapManager.addConnect(name, socket);
        // 更新在线状态
        userInfoManager.setOnlineState(name, true);
        socketListenOn(socket);

        return;
    }


});

// 客户端监听消息
function socketListenOn(socket) {
    const name = socket.handshake.query.name;

    //客户端断开连接
    socket.on('disconnect', (reason) => {
        console.log(`${name}disconnect , reason ${reason}`);

        // 删除连接信息
        socketConnectMapManager.deleteConnect(name);
        // 更新在线状态
        userInfoManager.setOnlineState(name, false);
    });

    // 接收到消息发送
    socket.on('sendMessage', (message) => {
        console.log(`receive message ${message}`);
        userInfoManager.addMessage(new userInfoManager.Message(message.sender, message.receiver, message.content, message.date));

        socket.emit('refreshChatContent', {
            friendName: message.receiver,
            messageHistory: userInfoManager.getMessageHistory(name, message.receiver)
        });

        // 如果好友在线则通知好友
        if (userInfoManager.getOnlineState(message.receiver)) {
            socketConnectMapManager.getUserSocket(message.receiver).emit('refreshChatContent', {
                friendName: message.sender,
                messageHistory: userInfoManager.getMessageHistory(message.receiver, name)
            });
        }

    });
    // 接收到请求历史消息
    socket.on('getMessageHistory', (message) => {
        console.log(`receive message ${message}`);

        friendName = message.friendName;
        socket.emit('refreshChatContent', {
            friendName: friendName,
            messageHistory: userInfoManager.getMessageHistory(name, friendName)
        });

    });
    // 接收到添加好友
    socket.on('addFriend', (friendInfo) => {
        console.log(`receive message ${friendInfo}`);
        if (userInfoManager.addFriend(name, friendInfo.friendName)) {
            socket.emit('addFriendResult', { result: true });

            // 如果好友在线则通知好友更新列表
            if (userInfoManager.getOnlineState(friendInfo.friendName)) {
                socketConnectMapManager.getUserSocket(friendInfo.friendName).emit('refreshFriendList', userInfoManager.getFriendList(friendInfo.friendName));
            }

            return;
        } else {
            socket.emit('addFriendResult', { result: false });
            return;
        }
    });

    // 获取好友列表
    socket.on('getFriendList', () => {
        console.log(`${name}  getFriendList`);
        friendList = userInfoManager.getFriendList(name);
        console.log(`${name} friend list ${friendList}`);
        socket.emit('refreshFriendList', friendList);
    });

}

server.listen(port, hostname, () => {
    console.log(`server running at http://${hostname}:${port}`);
})